package com.scfinance.SPD.externalReq;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;

import com.scfinance.SPD.util.Constants;
import com.scfinance.SPD.util.PropsUtil;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSONObject;
import com.scfinance.SPD.encrypt.DataEncrypt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by admin on 2017/6/27.
 */
public class SPDBankPAD {

    private static Logger logger = LoggerFactory.getLogger(SPDBankPAD.class);

    public static String sendReq(String url, String data) {
        String readLine = null;
        try {
            DefaultHttpClient httpclient = new DefaultHttpClient();
            // 请求超时
            httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);
            // 读取超时
            httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 10000);

            HttpPost httppost = new HttpPost(url);
            // 构造最简单的字符串数据
            StringEntity reqEntity = new StringEntity(new String(data), "UTF-8"); //一定为GBK
            // 设置类型
            reqEntity.setContentType("Content-Type = text/xml; charset=UTF-8");  //原为UTF-8
            // 设置请求的数据
            httppost.setEntity(reqEntity);
            // 执行
            try {
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    System.out.println(entity.getContentLength());
                }
                // 显示结果
                BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF8"));
                readLine = reader.readLine().trim();
                if (entity != null) {
                    EntityUtils.consume(entity);
                }
            } catch (ConnectTimeoutException e) {
                readLine = "";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return readLine;
    }

    /**
     * 图片混淆
     */
    public static byte[] confusion(byte data[]) {
        for (int i = 0; i < data.length; i++) {
            data[i] = (byte) (data[i] ^ 0xfd);
        }
        return data;
    }


    /**
     * 图片下载
     *
     * @param appid
     */
    public static void downloadImg(String appid) {
        File file = new File("D://test//" + appid + ".zip");
        String url = "http://172.29.40.174:8002/SPDBankServer/UploadServletZG" + "?fileName="
                + appid + ".zip" + "&command=download";
        HttpURLConnection httpURLConnection = null;
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            URL mUrl = new URL(url);
            httpURLConnection = (HttpURLConnection) mUrl.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setUseCaches(false);
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            inputStream = httpURLConnection.getInputStream();
            outputStream = new FileOutputStream(file);
            byte[] bytes = new byte[1024];
            int count = 0;
            while ((count = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, count);
            }

        } catch (Exception e) {
            System.out.println(e);
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (httpURLConnection != null) {
                httpURLConnection.disconnect();
            }
        }
    }

    /**
     * 图片上传
     * @param zipFileName
     * @param appid
     */
    public static String uploadImg(String zipFileName, String appid) {
        String returnStr = null;
        File file = new File(zipFileName);
        String url = PropsUtil.getProperty("SPDURL") + Constants.UPLOADIMG_SERVER + "?fileName="
                + appid + ".zip" + "&isNewFile=" + 0 + "&fullFileSize=" + file.length() + "&command=upload";
        HttpURLConnection httpURLConnection = null;
        try {
            URL mUrl = new URL(url);
            httpURLConnection = (HttpURLConnection) mUrl.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setUseCaches(false);
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setRequestProperty("Content-Type", "binary/octet-stream");
            OutputStream outputStream = httpURLConnection.getOutputStream();
            httpURLConnection.connect();
            if (file != null && file.exists()) {
                RandomAccessFile accessFile = new RandomAccessFile(
                        file, "r");
                byte[] bytes = new byte[1024*1024];
                int count = 0;
                while ((count = accessFile.read(bytes)) != -1) {
                    outputStream.write(bytes, 0, count);
                }
                int stateCode = httpURLConnection.getResponseCode();
                InputStream inputStream = null;
                if (stateCode == HttpURLConnection.HTTP_OK) {
                    inputStream = new BufferedInputStream(httpURLConnection.getInputStream());
                    bytes = new byte[1024];
                    count = inputStream.read(bytes);
                    returnStr = new String(bytes, 0, count);
                    System.out.println("上传图片返回消息：" + returnStr);
                }
                if (inputStream != null) {
                    inputStream.close();
                }
                accessFile.close();
            }
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            logger.info("错误", e);
            e.printStackTrace();
        } finally {
            if (httpURLConnection != null) {
                httpURLConnection.disconnect();
            }
        }
        return returnStr;
    }

    public static void queryDict() {
        String reqJson = "{\"dict\":\"CITYM\"}";
        String req = new DataEncrypt().encrypt("getDict", JSONObject.parseObject(reqJson), "0");
        System.out.println("请求参数:" + req);
        String s = sendReq("http://172.29.40.174:8002/SPDBankServer/MainServlet", req);
        System.out.println(new DataEncrypt().deEncrypt(s));
    }

    public static void queryActivitys() {
        String reqJson = "{\"citym\":\"NJ\",\"productId\":\"1027001\"}";
        String req = new DataEncrypt().encrypt("activitys", JSONObject.parseObject(reqJson), "0");
        System.out.println("请求参数:" + req);
        String s = sendReq("http://172.29.40.174:8002/SPDBankServer/MainServlet", req);
        System.out.println(new DataEncrypt().deEncrypt(s));
    }
}
